package com.adu.springbootdemo.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import com.adu.springbootdemo.domain.TemplateData;

public class VelocityUtil {
    public static void generate(VelocityContext velocityContext ,String fileName, String templateFile, String flag,TemplateData data) {
        StringWriter sw = new StringWriter();
        Template template = Velocity.getTemplate(templateFile);
        template.merge(velocityContext, sw);
        try {
            // 文件目录
            String path = String.format("targetFile/%s", templateFile.split("/")[2].split("\\.")[0]);
            // 文件类型：java、xml
            String type =  templateFile.split("/")[2].split("\\.")[1];
            // 文件类型名：UserController中的controller
            String typeName=templateFile.split("/")[2].split("\\.")[0];
            typeName=typeName.substring(0,1).toUpperCase()+typeName.substring(1);
            if(typeName.contains("Domain")){
                // 实体类不用加domain标识
                typeName="";
            }else if(typeName.contains("Mapperxml")){
                // mybatis的xml映射文件取消模板名中的xml字段
                typeName="Mapper";
                path=path.replace("mapperxml","mybatis");
            }else if(typeName.contains("Iservice")){
                typeName="Service";
                fileName="I"+fileName;
                path=path.replace("Iservice","service");
            }else if(typeName.contains("Service")){
                path=path.replace("service","service/Impl");
            }else if(typeName.contains("BaseController")){
                fileName="";
                path=path.replace("BaseController","controller");
            }else if(typeName.contains("Util")){
                fileName="";
                typeName=type;
                type="java";
            }else if(typeName.contains("SwaggerConfig")){
                fileName="";
            }else if(typeName.contains("Application")){
                if(type.equals("yml")){
                    typeName="application";
                    fileName="";
                }else{
                    fileName=data.getArtifact().substring(0,1).toUpperCase()+data.getArtifact().substring(1);
                    path=path.replace("Application","");
                }
            }else if(typeName.contains("Pom")){
                fileName="";
                typeName="pom";
            }

            File file = new File(path);
            if (!file.exists()) {
                file.mkdir();
            }
            System.out.println("fileName: "+path+"/"+fileName+typeName+"."+type);
            BufferedWriter out = new BufferedWriter(new FileWriter(path+"/"+fileName+typeName+"."+type));
            out.write(sw.toString());
            out.close();
            System.out.println("文件创建成功！");
        } catch (IOException e) {
        }
    }

    public static void Generate(TemplateData data,int num) {
        Properties p = new Properties();
        // 加载classpath目录下的vm文件
        p.setProperty("file.resource.loader.class",
                "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        // 定义字符集
        p.setProperty(Velocity.ENCODING_DEFAULT, "UTF-8");
        p.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
        p.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
        // 初始化Velocity引擎，指定配置Properties
        Velocity.init(p);
        VelocityContext velocityContext = new VelocityContext();

        velocityContext.put("data", data);
        List<String> templates = new ArrayList<>();
        templates.add("templates/java/controller.java.vm");
        templates.add("templates/java/domain.java.vm");
        templates.add("templates/java/mapper.java.vm");
        templates.add("templates/java/mapperxml.xml.vm");
        templates.add("templates/java/Iservice.java.vm");
        templates.add("templates/java/service.java.vm");

        templates.add("templates/system/Application.java.vm");
        templates.add("templates/system/BaseController.java.vm");
        templates.add("templates/system/application.yml.vm");
        templates.add("templates/system/util.JsonResult.java.vm");
        templates.add("templates/system/util.Result.java.vm");
        templates.add("templates/system/util.PageInfo.java.vm");
        templates.add("templates/system/pom.xml.vm");
        templates.add("templates/system/SwaggerConfig.java.vm");


        for (int i = 0; i < templates.size(); i++) {
            if(templates.get(i).contains("/java/")){
                generate(velocityContext, data.getClassName(), templates.get(i), "java",data);
            }else if(templates.get(i).contains("/system/") && num==0){
                // 项目单个文件（只生成一次）,num为0时，只生成
                generate(velocityContext, data.getClassName(), templates.get(i), "system",data);
            }

        }
//        TemplateData templateData = new TemplateData();
//        templateData.setName(generatePara.getDbConnectInfo().projectName);
//        templateData
//                .setPackageName(generatePara.getDbConnectInfo().group + "." + generatePara.getDbConnectInfo().artifact);
//        velocityContext.put("data", templateData);
//        String pom = "templates/system/pom.xml.vm";
//        Db item = new Db();
//        item.tableName = "";
//        generate(velocityContext, item, pom, "pom");
    }
}
